package com.java.simple.study.juc.p5;

import com.java.simple.study.tool.UnsafeUtil;
import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author zhoujunlin
 * @date 2022年07月05日 21:25
 * @desc
 */
public class UnsafeTest {

    public static void main(String[] args) throws NoSuchFieldException {
        Unsafe unsafe = UnsafeUtil.getUnsafe();
        // 获取成员属性
        Field id = Student.class.getDeclaredField("id");
        Field name = Student.class.getDeclaredField("name");
        // 获取成员变量偏移量
        long idOffset = unsafe.objectFieldOffset(id);
        long nameOffset = unsafe.objectFieldOffset(name);

        Student student = new Student();
        unsafe.compareAndSwapInt(student, idOffset, 0, 20);
        unsafe.compareAndSwapObject(student, nameOffset, null, "张三");
        System.out.println(student);
    }
}

@Data
class Student {
    volatile int id;
    volatile String name;
}
